package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.RpcRequest;
import com.lagou.service.IUserService;
import com.lagou.service.UserServiceImpl;
import com.lagou.utils.BeanUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest)msg;
        System.out.println();
        System.out.println("【服务端】接受信息："+JSON.toJSONString(rpcRequest));
        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Object[] parameters = rpcRequest.getParameters();
        //获取对象，获取方法，调用方法
        Object object = BeanUtils.getBeanByType(className);
        Method[] methods = object.getClass().getMethods();
        for (Method method : methods){
            if (method.getName().equalsIgnoreCase(methodName)){
                Object invoke = method.invoke(object, parameters);
                ctx.writeAndFlush(invoke);
            }
        }

        /*//注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则
        if(msg.toString().startsWith("UserService")){
            //2.如果符合规则,调用实现类货到一个result
            UserServiceImpl service = new UserServiceImpl();
            String result = service.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }*/


    }
}
